package com.application.followdroid;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;


public class Friends extends Activity {

	public String result;
	public String friend;
	public ArrayList<String> query_myuser = new ArrayList<String>();
	public ArrayList<Integer> query_isonline = new ArrayList<Integer>();
	public ArrayList<Integer> query_arefollowing = new ArrayList<Integer>();
	public String deleteit;
	
	private Intent loading_maps;
	private Intent login_friends;
	private String pkg_friends;
	private String pkg_loading_maps;
	private String user;
	private String follownow;
	private String user_select;
	
	private boolean rotateok=false;
	private ProgressDialog delete_friends;
	private ProgressDialog load_friends;
	private ProgressDialog update_follow;
	private ProgressDialog update_notfollow;
	
	public void onCreate(Bundle savedInstanceState) 
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.friends_follower);	
		
		login_friends=getIntent();
	    pkg_friends=getPackageName();
	    user=login_friends.getStringExtra(pkg_friends+".user_logged");
	    
	    pkg_loading_maps=getPackageName();
	    loading_maps=new Intent(getApplicationContext(), FollowDroid.class);
		
	    if(rotateok==false)
	    {
	    	update_listfriends();
	    }
	}


	//Riempie la ListView con i risultati della ricerca
	public void riempilista()
	{
		
		ListView lv = (ListView) findViewById(R.id.lvfriends);
     
        ArrayList<Person> personList=new ArrayList<Person>();

        Person people;
        for(int i=0;i<query_myuser.size();i++)
        {
        	//if(query_isonline.get(i)==0)
        	//{
        		if(query_arefollowing.get(i)==0)
        		{
        			//people=new Person(query_myuser.get(i),"",R.drawable.offline);
        			people=new Person(query_myuser.get(i),"No actions for this user",R.drawable.listuser);
        			personList.add(people);
        		}
        		else
        		{
        			//people=new Person(query_myuser.get(i),"You are following this user",R.drawable.offline);
        			people=new Person(query_myuser.get(i),"You are following this user",R.drawable.listuser);
            		personList.add(people);
        		}
        	//}
        	//else
        	//{
        	//	if(query_arefollowing.get(i)==0)
        	//	{
        	//		people=new Person(query_myuser.get(i),"",R.drawable.online);
        	//		personList.add(people);
        	//	}
        	//	else
        	//	{
        	//		people=new Person(query_myuser.get(i),"You are following this user",R.drawable.online);
            //		personList.add(people);
        	//	}
        	//}
        }
       
        ArrayList<HashMap<String, Object>> data=new ArrayList<HashMap<String,Object>>(); 
        for(int i=0;i<personList.size();i++)
        {
             Person p=personList.get(i);
             HashMap<String,Object> personMap=new HashMap<String, Object>();
                personMap.put("image", p.getPhotoRes());
                personMap.put("follow", p.getFollow());
                personMap.put("name", p.getName());
                data.add(personMap);
        }
       
        String[] from={"image","follow","name"};
        int[] to={R.id.personImage,R.id.personfollow,R.id.personName};
        
        SimpleAdapter adapter=new SimpleAdapter(
                        getApplicationContext(),
                        data,
                        R.layout.listtview_custom,
                        from,
                        to);
       
        ((ListView)findViewById(R.id.lvfriends)).setAdapter(adapter);
        
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() 
        {
        	public void onItemClick(AdapterView parent, View v,int position, long id)
            {
            	opzioniutente(position);
            }
        });
        
	}
	
	
	//opzioni al click dell'utente nella listview,passando come parametro la posizione nella listview
	public void opzioniutente(final int a)
	{
		SharedPreferences pref = getSharedPreferences("followme",MODE_PRIVATE);   
		follownow=pref.getString("user_follow",null);
		user_select=query_myuser.get(a);
		
		if(follownow==null)
		{
			final CharSequence[] friends = {"Follow now!","Delete"};
			AlertDialog.Builder builderfr = new AlertDialog.Builder(this);
	    	//builderfr.setTitle("My friends:");	
			builderfr.setItems(friends, new DialogInterface.OnClickListener() {
	    		public void onClick(DialogInterface dialog, int item) {
	    	        if(friends[item]=="Follow now!")
	    	        {
	    	        	getSharedPreferences("followme",MODE_PRIVATE)
	    		        .edit()
	    		        .putString("user_follow",query_myuser.get(a))
	    		        .commit();
	    	        	
	    	        	update_follow = ProgressDialog.show(Friends.this, "Loading...", "Wait please...", true,false);
	        			new Thread(new Runnable() 
	        			{
	        			    public void run() 
	        			    {
	    		    			deleteit=query_myuser.get(a);
	    		    			if(deleteit != null)
	    		    			{
	    		    				//Username e password da inviare al web service
	    		    	    		ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
	    		    	    		nameValuePairs.add(new BasicNameValuePair("myuser",user));
	    		    	    		nameValuePairs.add(new BasicNameValuePair("follow",deleteit));
	    		    	    		InputStream is=null;
	    		    		
	    		    	    		//Faccio il post http
	    		            		try
	    		            		{
	    		            			HttpClient httpclient = new DefaultHttpClient();
	    		            			HttpPost httppost = new HttpPost("http://followdroid.it/script/update_follow_myfriends.php");
	    		            			httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
	    		            			HttpResponse response = httpclient.execute(httppost);
	    		            	    	HttpEntity entity = response.getEntity();
	    		            	    	is = entity.getContent();
	    		                        
	    		            	    	handler_update_follow.sendEmptyMessage(1);
	    		            		}
	    		            		catch(Exception e)
	    		            		{
	    		            			handler_update_follow.sendEmptyMessage(2);
	    		            		}       	
	    		    	    	}
	    		    	    	else
	    		    	    	{
	    		    	    		handler_update_follow.sendEmptyMessage(0);
	    		    	    	}
	        			    }
	        			}).start();
	    	        	
	    	        	
	    	        	//finish();
	    	        }
	    	        if(friends[item]=="Delete")
	    	        {
	    	        	delete_friends = ProgressDialog.show(Friends.this, "Deleting...", "Wait please...", true,false);
	        			new Thread(new Runnable() 
	        			{
	        			    public void run() 
	        			    {
	    		    			deleteit=query_myuser.get(a);
	    		    			if(deleteit != null)
	    		    			{
	    		    				//Username e password da inviare al web service
	    		    	    		ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
	    		    	    		nameValuePairs.add(new BasicNameValuePair("myuser",user));
	    		    	    		nameValuePairs.add(new BasicNameValuePair("follow",deleteit));
	    		    	    		InputStream is=null;
	    		    		
	    		    	    		//Faccio il post http
	    		            		try
	    		            		{
	    		            			HttpClient httpclient = new DefaultHttpClient();
	    		            			HttpPost httppost = new HttpPost("http://followdroid.it/script/delete_whoifollow.php");
	    		            			httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
	    		            			HttpResponse response = httpclient.execute(httppost);
	    		            	    	HttpEntity entity = response.getEntity();
	    		            	    	is = entity.getContent();
	    		                        //refresh della lista
	    		            	    	query_myuser.remove(a);
	    		                        
	    		                        handler_delete.sendEmptyMessage(1);
	    		            	    	
	    		            		}
	    		            		catch(Exception e)
	    		            		{
	    		            			handler_delete.sendEmptyMessage(2);
	    		            		}       	
	    		    	    	}
	    		    	    	else
	    		    	    	{
	    		    	    		handler_delete.sendEmptyMessage(0);
	    		    	    	}
	        			    }
	        			}).start();
	    	        } 
	    	    }
	    	});
	    	AlertDialog viewtypefr = builderfr.create();
	    	viewtypefr.show();
		}
		else
		{
			if(follownow.equalsIgnoreCase(user_select))
			{
				final CharSequence[] friends = {"Don't follow"};
				AlertDialog.Builder builderfr = new AlertDialog.Builder(this);
		    	//builderfr.setTitle("My friends:");	
				builderfr.setItems(friends, new DialogInterface.OnClickListener() {
		    		public void onClick(DialogInterface dialog, int item) {
		    	        if(friends[item]=="Don't follow")
		    	        {
		    	        	getSharedPreferences("followme",MODE_PRIVATE)
		    		        .edit()
		    		        .putString("user_follow",null)
		    		        .commit();
		    	        	
		    	        	update_notfollow = ProgressDialog.show(Friends.this, "Loading...", "Wait please...", true,false);
		        			new Thread(new Runnable() 
		        			{
		        			    public void run() 
		        			    {
		    		    			deleteit=query_myuser.get(a);
		    		    			if(deleteit != null)
		    		    			{
		    		    				//Username e password da inviare al web service
		    		    	    		ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
		    		    	    		nameValuePairs.add(new BasicNameValuePair("myuser",user));
		    		    	    		nameValuePairs.add(new BasicNameValuePair("follow",deleteit));
		    		    	    		InputStream is=null;
		    		    		
		    		    	    		//Faccio il post http
		    		            		try
		    		            		{
		    		            			HttpClient httpclient = new DefaultHttpClient();
		    		            			HttpPost httppost = new HttpPost("http://followdroid.it/script/update_notfollow_myfriends.php");
		    		            			httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
		    		            			HttpResponse response = httpclient.execute(httppost);
		    		            	    	HttpEntity entity = response.getEntity();
		    		            	    	is = entity.getContent();
		    		                        
		    		            	    	handler_update_notfollow.sendEmptyMessage(1);
		    		            		}
		    		            		catch(Exception e)
		    		            		{
		    		            			handler_update_notfollow.sendEmptyMessage(2);
		    		            		}       	
		    		    	    	}
		    		    	    	else
		    		    	    	{
		    		    	    		handler_update_notfollow.sendEmptyMessage(0);
		    		    	    	}
		        			    }
		        			}).start();
		    	        	
		    	        	
		    	        	//finish();
		    	        }
		    	    }
		    	});
		    	AlertDialog viewtypefr = builderfr.create();
		    	viewtypefr.show();
			}
			else
			{
				final CharSequence[] friends = {"Delete"};
				AlertDialog.Builder builderfr = new AlertDialog.Builder(this);
		    	//builderfr.setTitle("My friends:");	
				builderfr.setItems(friends, new DialogInterface.OnClickListener() {
		    		public void onClick(DialogInterface dialog, int item) {
		    	        if(friends[item]=="Delete")
		    	        {
		    	        	delete_friends = ProgressDialog.show(Friends.this, "Deleting...", "Wait please...", true,false);
		        			new Thread(new Runnable() 
		        			{
		        			    public void run() 
		        			    {
		    		    			deleteit=query_myuser.get(a);
		    		    			if(deleteit != null)
		    		    			{
		    		    				//Username e password da inviare al web service
		    		    	    		ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
		    		    	    		nameValuePairs.add(new BasicNameValuePair("myuser",user));
		    		    	    		nameValuePairs.add(new BasicNameValuePair("follow",deleteit));
		    		    	    		InputStream is=null;
		    		    		
		    		    	    		//Faccio il post http
		    		            		try
		    		            		{
		    		            			HttpClient httpclient = new DefaultHttpClient();
		    		            			HttpPost httppost = new HttpPost("http://followdroid.it/script/delete_whoifollow.php");
		    		            			httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
		    		            			HttpResponse response = httpclient.execute(httppost);
		    		            	    	HttpEntity entity = response.getEntity();
		    		            	    	is = entity.getContent();
		    		                        //refresh della lista
		    		            	    	query_myuser.remove(a);
		    		                        //riempilista();
		    		                        handler_delete.sendEmptyMessage(1);
		    		            	    	
		    		            		}
		    		            		catch(Exception e)
		    		            		{
		    		            			handler_delete.sendEmptyMessage(2);
		    		            		}       	
		    		    	    	}
		    		    	    	else
		    		    	    	{
		    		    	    		handler_delete.sendEmptyMessage(0);
		    		    	    	}
		        			    }
		        			}).start();
		    	        }
		    	    }
		    	});
		    	AlertDialog viewtypefr = builderfr.create();
		    	viewtypefr.show();
			}
		}
	}	
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu)
	{
		super.onCreateOptionsMenu(menu);
		 menu.add(0,0,1,"Refresh").setIcon(R.drawable.refresh);
		return true;
	}
	
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		
		//Refresh lista degli amici
		case 0:
			rotateok=false;
			query_myuser.removeAll(query_myuser);
			update_listfriends();
		break;
		}
		return false;
	}
	
	public void update_listfriends()
	{
		load_friends = ProgressDialog.show(this, "Your friends...", "Loading...", true,false);
		new Thread(new Runnable() 
		{
		    public void run() 
		    {	
	        	//Username
	        	ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
	        	nameValuePairs.add(new BasicNameValuePair("myuser",user));
	        	InputStream is=null;
	        	//Faccio il post http
	        	try
	        	{
	        		HttpClient httpclient = new DefaultHttpClient();
	        	    HttpPost httppost = new HttpPost("http://followdroid.it/script/whoifollow.php");
	        	    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
	        	    HttpResponse response = httpclient.execute(httppost);
	        	    HttpEntity entity = response.getEntity();
	        	    is = entity.getContent();
	        	
	        	    //Converte la risposta HTTP in string
	        		BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
	        	    StringBuilder sb = new StringBuilder();
	        	    String line = null;
	        	    while ((line = reader.readLine()) != null) 
	        	    {
	        	    	sb.append(line + "\n");
	        	    }
	        	    is.close();
	        	    result=sb.toString();
	        	}
	        	catch(Exception e)
	        	{
	        		handler.sendEmptyMessage(2);
	        	}
	        	 
	        	//Metto insieme i dati JSON
	        	try
	        	{
	        	    JSONArray jArray = new JSONArray(result);
	        	    if(result!=null)
	        	    {
	        	    	for(int i=0;i<jArray.length();i++)
	        	    	{
	        	    		JSONObject json_data = jArray.getJSONObject(i);
	        	    		friend=json_data.getString("follow");
	        	    		query_myuser.add(i,json_data.getString("follow"));
	        	    		query_isonline.add(i,json_data.getInt("isonline"));
	        	    		query_arefollowing.add(i,json_data.getInt("arefollowing"));
	        	    	}
	        	    	handler.sendEmptyMessage(1);
	        	    }
	        	    else
	        	    {
	        	    	handler.sendEmptyMessage(0);
	        	    }
	        	}
	        	catch(JSONException e)
	        	{
	        		handler.sendEmptyMessage(0);
	        	}
		    }
		}).start();
	}
	
	@Override
	public void onBackPressed() 
	{
		finish();
		return;
	}
	
	private Handler handler_delete = new Handler() 
	{
	public void handleMessage(Message msg) {
		delete_friends.dismiss();
	    if (msg.what==1) 
	    {
	    	Toast.makeText(Friends.this, "You have Deleted "+deleteit, Toast.LENGTH_LONG).show();
	    	riempilista();
	    }
	    if (msg.what==0) 
	    {
	    	Toast.makeText(Friends.this, "You're not following anyone...Please add a friend and enjoy!", Toast.LENGTH_LONG).show();
	    }
	    
	    if (msg.what==2)
	    {
	    	//Errore
	    	Toast.makeText(Friends.this, "Error! Try again please...", Toast.LENGTH_LONG).show();
	    }
	}
	};
	
	private Handler handler_update_follow = new Handler() 
	{
		public void handleMessage(Message msg)
		{
			update_follow.dismiss();
		    if (msg.what==1) 
		    {
		    	loading_maps.putExtra(pkg_loading_maps+".user_logged",user );
	        	startActivity(loading_maps);
	        	onBackPressed();
		    }
		    if (msg.what==0) 
		    {
		    	Toast.makeText(Friends.this, "You're not following anyone...Please add a friend and enjoy", Toast.LENGTH_LONG).show();
		    }
		    
		    if (msg.what==2)
		    {
		    	//Errore
		    	Toast.makeText(Friends.this, "Error! Try again please...", Toast.LENGTH_LONG).show();
		    }
		}
	};
	
	private Handler handler_update_notfollow = new Handler() 
	{
		public void handleMessage(Message msg) 
		{
			update_notfollow.dismiss();
		    if (msg.what==1) 
		    {
		    	loading_maps.putExtra(pkg_loading_maps+".user_logged",user );
	        	startActivity(loading_maps);
	        	Toast dontfollow = Toast.makeText(Friends.this, "You don't follow "+follownow+" anymore!", Toast.LENGTH_LONG);
	        	dontfollow.show();	 
	        	onBackPressed();
		    }
		    if (msg.what==0) 
		    {
		    	Toast.makeText(Friends.this, "You're not following anyone...Please add a friend and enjoy", Toast.LENGTH_LONG).show();
		    }
		    
		    if (msg.what==2)
		    {
		    	//Errore di conversione
		    	Toast.makeText(Friends.this, "Error! Try again please...", Toast.LENGTH_LONG).show();
		    }
		}
	};
	
	private Handler handler = new Handler() 
	{
		public void handleMessage(Message msg) 
		{
			load_friends.dismiss();
		    if (msg.what==1) 
		    {
		    	Toast.makeText(Friends.this, "Your friends", Toast.LENGTH_SHORT).show();
		    	riempilista();
		    } 
		    if (msg.what==0) 
		    {
		    	Toast.makeText(Friends.this, "You're not following anyone ... Please add a friend and enjoy", Toast.LENGTH_LONG).show();
		    }
		    if (msg.what==2)
		    {
		    	//Errore
		    	Toast.makeText(Friends.this, "Error! Try again please...", Toast.LENGTH_LONG).show();
		    }
		}
	}; 

	@Override
	public void onConfigurationChanged(Configuration newConfig) 
	{
		super.onConfigurationChanged(newConfig);
		rotateok=true;
	}
}


